<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Models\Blog\Article;
use App\Models\Blog\Comment;
use App\Models\Common\FailedJob;
use App\Models\Common\Region;
use App\Models\Expansion\Chat;
use App\Models\Expansion\Delete;
use App\Models\Expansion\EmailReceive;
use App\Models\Mongo\Admin;
use App\Models\Mongo\Blog;
use App\Models\System\Info;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use LaraMall\Admin\Sysinfo\Sysinfo;

class HomeService
{
    use Service;

    /**
     * 清除缓存
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function CacheService( Request $request )
    {
        $base = base_path();
        switch ( $request->input('status', 'all') ) {
            case 'all':
                exec("php $base/artisan config:cache");
                exec("php $base/artisan route:cache");
                exec("php $base/artisan view:clear");
                exec("php $base/artisan cache:clear");
                break;
            case 'config':
                exec("php $base/artisan config:cache");
                break;
            case 'route':
                exec("php $base/artisan route:cache");
                break;
            case 'view':
                exec("php $base/artisan view:clear");
                break;
            case 'cache':
                exec("php $base/artisan cache:clear");
                break;
            default:
                break;
        }
        return data();
    }

    /**
     * 获取省市区或者搜索省市区
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function RegionCodeService( $request )
    {
        $where  = function ( $query ) use ( $request ) {
            if ( $request->filled('name') ) $query->where('name', $request->input('name'));
            else {
                if ( $request->filled('parent_id') ) $query->where('parent_id', $request->input('parent_id'));
                $query->where('type', $request->input('type', 1));
            }
        };
        $select = [ 'id', 'name', 'parent_id', 'type' ];
        $data   = Region::GetModel($where, [], $select);
        return data($data);
    }

    /**
     * 获取邀请数据
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserService( $request )
    {
        $where  = function ( $query ) use ( $request ) {
            $query->where('is_show', $request->input('is_show', 1));
            $query->where('static', $request->input('static', 1));
        };
        $select = [ 'id', 'name', 'email' ];
        $data   = User::GetModel($where, [], $select);
        return data($data);
    }


    /**
     * 写入文件 下载
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function TextFileService( $request )
    {
        $disk = $this->getStorage();
        if ( $request->filled('is_show') ) $where = function ( $query ) use ( $request ) { $query->where('is_show', $request->input('is_show')); };
        else $where = [];
        $ext = $request->input('ext');
        switch ( $request->input('id') ) {
            case 'admin':
                $file  = $request->input('id') . $ext;
                $table = Admin::GetModel();
                break;
            case 'blog':
                $file  = $request->input('id') . $ext;
                $table = Blog::GetModel();
                break;
            default:
                $file  = $request->input('table') . $ext;
                $table = DB::table($request->input('table'))->where($where)->get()->toArray();
                break;
        }
        if ( $request->filled('is_show') ) $file = $request->input('table') . '-' . $request->input('is_show') . $ext;
        $error = $this->getErrorCode();
        if ( ! $table ) abort(500, $error::message(1013));
        $user     = Auth::user();
        $ext      = strtolower(pathinfo($ext, PATHINFO_EXTENSION));
        $savePath = 'download' . '/' . $user->name . '/' . $user->id . '/' . $ext . '/' . $file;
        $disk->disk('storage');
        if ( $disk->exists($savePath) ) return $disk->download($savePath);
        $disk->makeDirectory('download/' . $user->name . '/' . $user->id . '/' . $ext);
        switch ( $ext ) {
            case 'txt':
                if ( ! TextFile($disk->fileUrl($savePath), $table) ) abort(500, $error::message(1014));
                break;
            case 'xlsx':
                if ( ! ExcelFile($disk->fileUrl($savePath), $table) ) abort(500, $error::message(1014));
                break;
            default:
                abort(404, $error::message(1013));
                break;
        }
        $data[ 'uid' ]  = Auth::id();
        $data[ 'name' ] = $savePath;
        $data[ 'size' ] = maxsize($disk->size($savePath));
        Delete::CreateModel($data);
        return $disk->download($savePath);
    }

    /**
     * 发送验证码
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function EmailCodeService( $request )
    {
        $validate = $this->getAdminValidator();
        $error    = $this->getErrorCode();
        $username = $request->input('username');
        switch ( $request->input('status') ) {
            case 'a':
                $where = function ( $query ) use ( $request, $username ) {
                    $query->where('email', $username);
                    $query->whereNotNull('email');
                    $query->where('is_show', 1);
                    $query->where('id', '<>', $request->input('uid'));
                };
                if ( User::ExistsModel($where) ) return message($error::message(1003));
                break;
            case 'b':
                request()->offsetSet('email', $username);
                $validator = $validate->EmailCodeValidator($request);//Validator验证
                if ( $validator->first() ) return message($validator->first());
                break;
            case 'c':
                request()->offsetSet('email', $username);
                $validator = $validate->UserEmailCodeValidator($request);//Validator验证
                if ( $validator->first() ) return message($validator->first());
                break;
            case 'd':
                request()->offsetSet('email', $username);
                $validator = $validate->UserEmailCodeUpdateValidator($request);//Validator验证
                if ( $validator->first() ) return message($validator->first());
                break;
            default:
                return message($error::message(1001));
                break;
        }
        $code              = GetRandStr();//随机验证码
        $data[ 'name' ]    = '发送验证码';
        $data[ 'email' ]   = $username;
        $data[ 'content' ] = "您的验证码是 $code 验证码10分钟内有效";
        $data[ 'id' ]      = FALSE;
        $key               = 'queues:default:reserved';
        $value             = json_encode($data);
        $json              = implode(',', [ $code, $username, Auth::id() ]);
        Cookie::queue('username_' . $request->input('id'), $json, 10);//取Cookie值
        $success[ '验证码' ]  = $code;
        $success[ '邮箱号' ]  = $username;
        $success[ '用户id' ] = Auth::id();
        $success[ '内容' ]   = $data[ 'content' ];
        FailedJob::CreateModel([ 'key' => $key, 'content' => $value ]);
        errorStorage('code', $success, '发送验证码成功', 'success', '发送验证码');
        return data(NULL, $error::message(201));
    }


    /**
     * 获取服务器信息
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function SysInfoService( $request )
    {
        $sys      = new Sysinfo();//获取系统信息插件
        $json     = file_get_contents(base_path('composer.json'));//获取json文件内容
        $composer = json_decode($json, TRUE)[ 'require' ];//解析
        $apache   = [
            [
                'name'  => 'PHP version',
                'value' => 'PHP/' . PHP_VERSION,
            ],
            [
                'name'  => 'Laravel version',
                'value' => app()->version(),
            ],
            [
                'name'  => 'CGI',
                'value' => php_sapi_name(),
            ],
            [
                'name'  => 'UName',
                'value' => php_uname(),
            ],
            [
                'name'  => 'Server',
                'value' => array_get($_SERVER, 'SERVER_SOFTWARE'),
            ],
            [
                'name'  => 'Cache driver',
                'value' => config('cache.default'),
            ],
            [
                'name'  => 'Session driver',
                'value' => config('session.driver'),
            ],
            [
                'name'  => 'Queue driver',
                'value' => config('queue.default'),
            ],
            [
                'name'  => 'Timezone',
                'value' => config('app.timezone'),
            ],
            [
                'name'  => 'Locale',
                'value' => config('app.locale'),
            ],
            [
                'name'  => 'Env',
                'value' => config('app.env'),
            ],
            [
                'name'  => 'URL',
                'value' => config('app.url'),
            ],
            [
                'name'  => 'cpu',
                'value' => $sys->cpu(),
            ],
            [
                'name'  => 'memory',
                'value' => $sys->memory(),
            ],
            [
                'name'  => 'ip',
                'value' => $sys->ip(),
            ],
            [
                'name'  => 'safeMode',
                'value' => $sys->safeMode(),
            ],
            [
                'name'  => 'uploadMaxsize',
                'value' => $sys->upload_max_filesize(),
            ],
            [
                'name'  => 'mysql',
                'value' => $sys->mysql(),
            ],
        ];
        switch ( $request->input('category', 0) ) {
            case 1:
                $where                 = function ( $query ) {
                    $query->where('is_show', 2);
                };
                $where1                = function ( $query ) {
                    $query->where('static', 1);
                    $query->where('status', 3);
                };
                $where2                = function ( $query ) {
                    $query->where('static', 2);
                    $query->where('status', 1);
                };
                $count[ 0 ][ 'color' ] = 'org';
                $count[ 0 ][ 'icon' ]  = '&#xe606;';
                $count[ 0 ][ 'name' ]  = '用户';
                $count[ 0 ][ 'value' ] = User::CountModel($where);
                $count[ 1 ][ 'color' ] = 'blue';
                $count[ 1 ][ 'icon' ]  = '&#xe602;';
                $count[ 1 ][ 'name' ]  = '文章';
                $count[ 1 ][ 'value' ] = Article::CountModel($where1);
                $count[ 2 ][ 'color' ] = 'green';
                $count[ 2 ][ 'icon' ]  = '&#xe605;';
                $count[ 2 ][ 'name' ]  = '评论';
                $count[ 2 ][ 'value' ] = Comment::CountModel($where2);
                break;
            default:
                $where                 = function ( $query ) {
                    $query->where('is_show', 1);
                };
                $count[ 0 ][ 'color' ] = 'org';
                $count[ 0 ][ 'icon' ]  = '&#xe606;';
                $count[ 0 ][ 'name' ]  = '用户';
                $count[ 0 ][ 'value' ] = User::CountModel($where);
                $count[ 1 ][ 'color' ] = 'blue';
                $count[ 1 ][ 'icon' ]  = '&#xe603;';
                $count[ 1 ][ 'name' ]  = '邮件';
                $count[ 1 ][ 'value' ] = EmailReceive::CountModel();
                $count[ 2 ][ 'color' ] = 'green';
                $count[ 2 ][ 'icon' ]  = '&#xe60c;';
                $count[ 2 ][ 'name' ]  = '聊天消息';
                $count[ 2 ][ 'value' ] = Chat::CountModel();
                break;
        }
        $group = [];
        $user  = Info::GroupModel('province');
        $i     = 0;
        foreach ( $user as $value ) {
            if ( ! $value->province ) continue;
            $group[ $i ][ 'name' ]  = Region::ValueModel([ 'id' => $value->province ], 'name');
            $group[ $i ][ 'count' ] = Info::CountModel([ 'province' => $value->province ]);
            $i++;
        }
        unset($user);
        $collect = collect($group);
        $Ranking = $collect->sortByDesc('count')->take(6)->values()->toArray();
        unset($collect);
        return view('home', compact('apache', 'composer', 'count', 'request', 'Ranking'));
    }

}
